<template>
  <el-card>
    <div>
      <el-form
        ref="setmealFormRef"
        :model="setmealForm"
        :rules="setmealRules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="套餐名称:" prop="name">
              <el-input
                v-model="setmealForm.name"
                placeholder="请填写套餐名称"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜品分类:" prop="categoryId">
              <el-select
                v-model="setmealForm.categoryId"
                placeholder="请选择菜品分类"
              >
                <el-option
                  v-for="(item, index) in categoryList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜品价格:" prop="price">
              <el-input
                v-model="setmealForm.price"
                placeholder="请设置菜品价格"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 添加菜品 - BEGIN -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="菜品明细:">
              <div v-if="dishSelectedList.length == 0">
                <el-button type="warning" @click="onAddDishToSetmeal"
                  >添加菜品</el-button
                >
              </div>
              <div v-else style="background-color: pink">
                <el-table :data="dishSelectedList">
                  <el-table-column label="菜品名称" :width="200" prop="name">
                  </el-table-column>
                  <el-table-column label="原价" prop="price">
                    <template #default="scope">
                      <strong
                        >&yen;&nbsp;{{ Number(scope.row.price / 100) }}</strong
                      >
                    </template>
                  </el-table-column>
                  <el-table-column label="数量" :width="200" prop="copies">
                    <template #default="scope">
                      <el-input-number
                        v-model="scope.row.copies"
                        :step="1"
                        step-strictly
                        :min="1"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column :width="100" label="操作">
                    <template #default="scope">
                      <el-button
                        type="danger"
                        @click="delDishFromSelectedList(scope.row.id)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 添加菜品 END -->

        <el-row>
          <el-col :span="6">
            <el-form-item label="菜品图片:" prop="image">
              <el-upload
                class="avatar-uploader"
                action="/api/common/upload"
                :show-file-list="false"
                :on-success="handleDishImgSuccess"
                ref="uploadRef"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="菜品描述:" prop="description">
              <el-input
                v-model="setmealForm.description"
                type="textarea"
                :rows="4"
                placeholder="菜品描述，最长200字"
                maxlength="200"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="submitForm()"> 保存 </el-button>
    </div>
  </el-card>
  <DishSelect ref="dishSelectRef" @dishAddSuccess="handleDishAddSuccess" />
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { defineOptions } from 'vue'
import { reqGetCategoryListNoPage } from '@/api/category'
import {
  reqAddSetmeal,
  reqGetSetmealById,
  reqUpdateSetmeal
} from '@/api/setmeal'
import DishSelect from './DishSelect.vue'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
defineOptions({
  name: 'SetmealAddEdit'
})

const routes = useRoute()
const router = useRouter()
const actionType = ref('add')

onMounted(() => {
  getCategoryList()
  //获取路径中的参数,如果能获取到id，就是修改；否则是新增
  const setmealId = routes.params.id
  if (setmealId) {
    getSetmealById(setmealId)
    // 将setmealId保持到表单中
    setmealForm.value.id = setmealId
    //设置操作类型是update
    actionType.value = 'update'
  } else {
    actionType.value = 'add'
    //清空dishForm数据
    setmealForm.value = {
      id: '',
      name: '', //套餐名称
      categoryId: null, //套餐分类
      price: '', //价格
      code: '', //商品码（保留字段）
      setmealDishes: [], //本套餐中包含的菜品列表
      image: '', //套餐图片
      description: '', //套餐描述
      status: true, //销售状态
      idType: '' //套餐分类
    }
    //清空图像
    imageUrl.value = ''
  }
})

const getSetmealById = async (id) => {
  const res = await reqGetSetmealById(id)
  setmealForm.value = res.data.data
  //price处理
  setmealForm.value.price = String(setmealForm.value.price / 100)
  //设置图像
  imageUrl.value = `/api/common/download?name=${setmealForm.value.image}`
  //设置套餐中包含的菜品列表
  dishSelectedList.value = setmealForm.value.setmealDishes
}
//获取套餐分类列表
const categoryList = ref([])
const getCategoryList = async () => {
  // type: 2 是套餐分类；type: 1 是菜品分类
  const res = await reqGetCategoryListNoPage({ type: 2 })
  categoryList.value = res.data.data
}

// 菜品图片上传
import { Plus } from '@element-plus/icons-vue'
const imageUrl = ref('')
// 上传成功，则加载图片
const handleDishImgSuccess = (response, file, fileList) => {
  // 拼接download接口预览
  if (response.code === 0 && response.msg === '未登录') {
    console.log('未登录')
  } else {
    imageUrl.value = `/api/common/download?name=${response.data}`
    setmealForm.value.image = response.data
  }
}
//dish表单
const setmealForm = ref({
  id: '',
  name: '', //套餐名称
  categoryId: null, //套餐分类
  price: '', //价格
  code: '', //商品码（保留字段）
  setmealDishes: [], //本套餐中包含的菜品列表
  image: '', //套餐图片
  description: '', //套餐描述
  status: true, //销售状态
  idType: '' //套餐分类
})

//接收从子组件中传递来的选中菜品
const dishSelectedList = ref([])
const handleDishAddSuccess = (list) => {
  //TODO: 赋值可以优化一下
  dishSelectedList.value = list

  //   console.log(dishSelectedList.value)
}

// 表单校验规则
const setmealRules = reactive({
  name: [{ required: true, message: '请填写套餐名称', trigger: 'blur' }],
  categoryId: [
    { required: true, message: '请选择套餐分类', trigger: 'change' }
  ],
  price: [
    {
      required: true,
      // 'message': '请填写套餐价格', 使用下面的自定义校验
      validator: (rules, value, callback) => {
        if (!value) {
          callback(new Error('请填写套餐价格'))
        } else {
          const reg = /^\d+(\.\d{0,2})?$/
          if (reg.test(value)) {
            if (value < 10000) {
              callback()
            } else {
              callback(new Error('套餐价格应小于10000'))
            }
          } else {
            callback(new Error('套餐价格的格式只能为数字,且最多保留两位小数'))
          }
        }
      },
      trigger: 'blur'
    }
  ]
})
//向套餐中添加菜品
const dishSelectRef = ref(null)
const onAddDishToSetmeal = () => {
  dishSelectRef.value.open()
}

// 从套餐中删除菜品
const delDishFromSelectedList = (dishId) => {
  dishSelectedList.value = dishSelectedList.value.filter((dish) => {
    return dish.id !== dishId
  })
}

//提交表单
const setmealFormRef = ref(null)
const submitForm = () => {
  setmealFormRef.value.validate(async (valid) => {
    //如果表单验证通过，则valid为true
    if (valid) {
      //组装请求数据
      let setmealData = { ...setmealForm.value }
      setmealData.status = 1 //起售
      setmealData.price *= 100 //元-->分
      // 处理本套餐中包含的菜品，将id改为dishId，
      // 因为dish表中id字段，到了setmeal_dish表就成了dish_id字段
      dishSelectedList.value = dishSelectedList.value.map((dish) => {
        dish.dishId = dish.id
        delete dish.id
        return { ...dish }
      })
      console.log('本套餐中包含的菜品列表：', dishSelectedList.value)
      // 处理本套餐中的菜品列表
      setmealData.setmealDishes = dishSelectedList.value

      if (!imageUrl.value) {
        ElMessage.error('请上传套餐的图片')
        return
      }
      if (actionType.value == 'add') {
        delete setmealData.id
        //发送添加菜品请求
        // console.log(setmealData)
        const res = await reqAddSetmeal(setmealData)
        //清空dishForm数据
        setmealForm.value = {
          id: '',
          name: '', //套餐名称
          // categoryId: '', //套餐分类（避免初始校验出错）
          price: '', //价格
          code: '', //商品码（保留字段）
          setmealDishes: [], //本套餐中包含的菜品列表
          image: '', //套餐图片
          description: '', //套餐描述
          status: true, //销售状态
          idType: '' //套餐分类
        }
        //给出成功的消息提示
        ElMessage.success(res.data.msg || '新增套餐成功！')
        // 跳转路由
        router.push('/setmeal')
      } else {
        //删除更新时间字段
        delete setmealData.updateTime
        //发送修改菜品请求
        const res = await reqUpdateSetmeal(setmealData)
        //给出成功的消息提示、关闭窗口
        ElMessage.success(res.data.msg || '修改套餐成功！')
        // 跳转路由
        router.push('/setmeal')
      }
    } else {
      return false
    }
  })
}

//取消修改，返回列表页

const onCancel = () => {
  router.push('/setmeal')
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>
